package com.example.demo;

import com.example.demo.domain.TodoList;
import com.example.demo.mapper.TodoListMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.server.PathParam;
import java.util.UUID;

@RestController
@RequestMapping("/")
@CrossOrigin
public class Hello {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private TodoListMapper mapper;

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public Object hello() {
        String sql = "select count(1) from EMP";
        return jdbcTemplate.queryForMap(sql);
    }

    @RequestMapping(value = "/count", method = RequestMethod.GET)
    public Integer queryCount() {
        return mapper.selectCount();
    }

    @RequestMapping(value = "/add_todo", method = RequestMethod.GET)
    @Transactional
    public Integer addTodo(@PathParam("name") String name) {
        TodoList todoList = new TodoList();
        todoList.setId(UUID.randomUUID().toString());
        todoList.setName(name);
        return mapper.insertTodo(todoList);
    }

    @RequestMapping(value = "/delete_todo", method = RequestMethod.GET)
    @Transactional
    public Integer deleteTodo(@PathParam("id") String id) {
        return mapper.deleteTodoById(id);
    }

    @RequestMapping(value = "/update_todo", method = RequestMethod.GET)
    @Transactional
    public Integer updateTodo(@PathParam("id") String id, @PathParam("name") String name) {
        TodoList todoList = new TodoList();
        todoList.setId(id);
        todoList.setName(name);
        return mapper.updateTodo(todoList);
    }

    @RequestMapping(value = "/query_todo", method = RequestMethod.GET)
    public Object queryTodo(@PathParam("name") String name) {
        return mapper.queryTodoListByName(name);
    }
}
